const NeedLogin = require('../need_login.js');

module.exports = class extends NeedLogin {
  async indexAction() {
    try {
      var ajaxData;
      if(this.isGet) ajaxData = this.get()
      if(this.isPost) ajaxData = this.post()
      if (ajaxData.uid == ajaxData.to_id) {
        return this.json({
          status: -1,
          msg: '不能关注自己'
        }) 
      }
      var userdb = this.mongoose('mongo/sn_users')
      var to_id = think.objId(ajaxData.to_id);
      // 查询目标用户是否存在
      var findToUser = await userdb.find({_id: to_id, status: 1})
      console.log(findToUser)
      if (findToUser.length <= 0) {
        return this.json({
          status: -1,
          msg: '目标用户不存在或已封禁'
        })
      }
      var fansdb = this.mongoose('mongo/sn_users_fans')
      var fingUserFans = await fansdb.find({uid: ajaxData.uid, to_id: ajaxData.to_id});
      var current;
      if (fingUserFans.length > 0) {
        await fansdb.update({
          uid: ajaxData.uid,
          to_id: ajaxData.to_id
        }, {
          status: fingUserFans[0].status == 1 ? 0 : 1
        })
        current = fingUserFans[0].status == 1 ? 0 : 1
      } else {
        console.log('没有数据新建保存')
        var newFans = new fansdb({
          uid: ajaxData.uid,
          to_id: ajaxData.to_id
        })
        var a = await newFans.save()
        current = 1
      }
      var findFansCount = await fansdb.find({
        to_id: ajaxData.to_id,
        status: 1
      }).count()
      return this.json({
        status: 1,
        current: current,
        count: findFansCount
      })
    } catch (e) {
      return this.json({
        status: -2,
        msg: e.message
      })
    }
  }
};
